<?php
namespace app\api\controller\order;

use app\api\controller\Api;
use app\common\audit\logic\AuditResultLogic;
use app\common\order\model\Order;
use app\common\order\model\OrderIncome;
use app\common\order\validate\OrderIncomeValidate;
use app\common\system\model\OperateLog;
use Exception;
use think\db\exception\DbException;

class Income extends Api {
    
    public function getList() {
        $post = $this->request->post();
        if (empty($post['order_id'])) return error([], "参数错误");

        $orderModel = new Order();
        $order = $orderModel->where('id', $post['order_id'])->find();
        if (empty($order)) {
            return error([], "订单已不存在");
        }

        $where = [];
        if ($order['pid'] > 0) {
            $where[] = ['order_id', 'in', [$order['id'], $order['pid']]];
        } else {
            $where[] = ['order_id', '=', $order['id']];
        }
        $model = new OrderIncome();
        $list = $model->where($where)->order('id desc')->select();
        foreach($list as $row) {
            $row->append(['way', 'type', 'user', 'check_tag', 'receipt', 'note']);
        }
        $result['list'] = $list;

        return success($result);
    }

    public function create() {
        $post = $this->request->post();
        $user = $this->request->user;

        // 验证收款信息
        $income = $post['income'];
        $incomeValidate = new OrderIncomeValidate();
        if (!$incomeValidate->check($income)) {
            return error([], $incomeValidate->getError());
        }

        $source = [];
        // 收款信息
        $income['user_id'] = $user['id'];
        $model = new OrderIncome();
        $model->startTrans();

        $modelName = OrderIncome::class;
        try {
            $model->save($income);
            $source[$modelName] = $model->id;
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $orderModel = new Order();
        $order = $orderModel->where('id', $income['order_id'])->find();

        $auditRsLogic = new AuditResultLogic();
        $master = $order->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'income'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className=>$row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '操作成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function save() {
        $post = $this->request->post();
        $user = $this->request->user;

        // 验证收款信息
        $income = $post['income'];
        $incomeValidate = new OrderIncomeValidate();
        if (!$incomeValidate->check($income)) {
            return error([], $incomeValidate->getError());
        }

        $source = [];
        // 收款信息
        $income['user_id'] = $user['id'];
        $model = new OrderIncome();
        $model->startTrans();

        $modelName = OrderIncome::class;
        try {
            $row = $model->where('id', $income['id'])->find();
            $row->save($income);
            $source[$modelName] = $income['id'];
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        $orderModel = new Order();
        $order = $orderModel->where('id', $income['order_id'])->find();

        $auditRsLogic = new AuditResultLogic();
        $master = $order->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'income'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className=>$row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '操作成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function update()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        // 验证收款信息
        $income = $post['income'];
        $incomeValidate = new OrderIncomeValidate();
        if (!$incomeValidate->check($income)) {
            return error([], $incomeValidate->getError());
        }

        // 收款信息
        $income['user_id'] = $user['id'];
        $model = new OrderIncome();

        $model->startTrans();
        try {
            $row = $model->where('id', $income['id'])->find();
            $origin = $row->getData();
            $row->save($income);

            $changed = $row->getData();
            $modelName = OrderIncome::class;
            OperateLog::write($user['id'], $income['order_id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], "操作成功");
    }
}